package cndw.core.dispatch;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import cndw.core.util.annotation.ThreadSafe;

/**
 * Request引用保存在线程本地变量中,提供更简单的方式设置和获取request
 * @author zuojie.x
 */
@ThreadSafe
class ThreadLocalRequest {
	private final Map<Thread, ThreadLocal<Request>> threadLocals;
	
	private static class ThreadLocalRequestHolder {
		private static ThreadLocalRequest localRequest = new ThreadLocalRequest ();
	}
	
	private ThreadLocalRequest() {
		threadLocals = new ConcurrentHashMap<Thread, ThreadLocal<Request>>();
	}
	
	/**
	 * @return {@link ThreadLocalRequest}实例
	 */
	private static ThreadLocalRequest instance() {
		return ThreadLocalRequestHolder.localRequest;
	}
	
	/**
	 * 设置Request引用到线程本地变量
	 * @param request
	 */
	public static void set(Request request) {
		ThreadLocalRequest localRequest = instance();
		Thread thread = Thread.currentThread();
		ThreadLocal<Request> local = localRequest.threadLocals.get(thread);
		if (local == null) {
			local = new ThreadLocal<Request>();
			localRequest.threadLocals.put(thread, local);
		}
		local.set(request);
	}
	
	/**
	 * @return 线程本地变量中获取Request引用
	 */
	public static Request get() {
		return getThreadLocal().get();
	}
	
	/**
	 * 线程本地变量中删除Request引用
	 */
	public static void remove() {
		getThreadLocal().remove();
	}
	
	/**
	 * @return {@link ThreadLocal}
	 */
	private static ThreadLocal<Request> getThreadLocal() {
		ThreadLocalRequest localRequest = instance();
		Thread thread = Thread.currentThread();
		return localRequest.threadLocals.get(thread);
	}
}
